package com.lucas.Handler;

import com.lucas.Service.UserServiceImpl;
import com.lucas.service.UserService;
import com.lucsa.pojo.RpcRequest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.Callable;

@Component
@ChannelHandler.Sharable
public class UserServerHandler extends ChannelInboundHandlerAdapter implements BeanFactoryAware {

    private BeanFactory beanFactory;


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //判断msg的信息
//        if(msg.toString().startsWith("userService")){
//            String result = new UserServiceImpl().sayHello(msg.toString().substring(msg.toString().lastIndexOf("#")+1));
//            ctx.writeAndFlush("服务端收到客户端信息了,客户端信息为:"+result+" ,服务端正在发送信息给客户端");
//        }

        System.out.println("====进入了服务器端的handler=====");
        final RpcRequest rpcRequest = (RpcRequest)msg;
        final String className = rpcRequest.getClassName();


            Class<?> aClass = Class.forName(className);//com.lucas
            Object bean =  beanFactory.getBean(aClass);
            String methodName = rpcRequest.getMethodName();
            Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
            Object[] parameters = rpcRequest.getParameters();
            Method method = aClass.getMethod(methodName,parameterTypes);
            String  invoke = (String )method.invoke(bean, parameters);
            System.out.println("====调用了服务器端的方法,获得结果:"+invoke+"========");
//            String  result =new UserServiceImpl().sayHello(rpcRequest);
           //发送的数据格式不一致,就无法读取
//            ctx.writeAndFlush("服务端收到客户端信息了,客户端信息为:"+result+" ,服务端正在发送信息给客户端....");
            ctx.writeAndFlush(rpcRequest);

    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public BeanFactory getBeanFactory() {
        return beanFactory;
    }
}
